package com.techysky.share;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;


import org.apache.commons.lang3.StringUtils;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

public class ShareFile implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	public static void main(String[] args) {  
		shareWriter("smb://Administrator:123456@172.16.50.89/安装包", "E://sonar2.txt") ;    
    }  
	
	
	//读取文件
	public static void shareReader(String url) throws IOException {
		SmbFile remoteFile = new SmbFile(url);
		remoteFile.connect();
		try(InputStream in=new BufferedInputStream(new SmbFileInputStream(remoteFile))){
			 BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));  
	            String tmp=reader.readLine();  
	            while(StringUtils.isNotEmpty(tmp)){  
	                tmp=reader.readLine();  
	            }  
		}catch(Exception e) {
			Logger.getLogger(ShareFile.class.getName()).log(Level.SEVERE, "共享文件读取有误", e);
		}
	}
	//上传写入共享文件
	public static boolean shareWriter(String url,String location) {
		File file=new File(location);
		String fileName=file.getName();
		try(InputStream in=new BufferedInputStream(new FileInputStream(file));
			OutputStream out=new BufferedOutputStream(new SmbFileOutputStream( new SmbFile(url + "/" + fileName)));
				){
			  byte[] buffer = new byte[1024];  
	            while (in.read(buffer) != -1) {  
	                out.write(buffer);  
	                buffer = new byte[1024];  
	            }  
	            return true;  
		}catch(Exception e) {
			Logger.getLogger(ShareFile.class.getName()).log(Level.SEVERE, "共享文件写入有误", e);
			return false;
		}
	}
}
